package com.o.mj.controller;

import com.o.mj.pojo.Login;
import com.o.mj.pojo.UserInfo;
import com.o.mj.service.LoginService;
import com.o.mj.service.PersonService;
import com.o.mj.service.WorkPersonService;
import com.o.mj.util.Md5Util;
import com.o.mj.util.exception.R;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * 个人信息控制
 */

@Controller
public class PersonController extends HttpServlet {

    @Autowired
    WorkPersonService workPS;

    @Autowired
    LoginService loginService;

    @Autowired
    PersonService personS;
    private static final long serialVersionUID = 1L;

    /**
     * 设置个人头像
     */
    @PostMapping("/UploadServlet.do")
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 判断上传表单是否为multipart/form-data类型
        HttpSession session = request.getSession();
        Object user = session.getAttribute("userId"); // 在登录时将 User 对象放入了 会话
        if (ServletFileUpload.isMultipartContent(request)) {

            try {
                // 1. 创建DiskFileItemFactory对象，设置缓冲区大小和临时文件目录
                DiskFileItemFactory factory = new DiskFileItemFactory();
                // System.out.println(System.getProperty("java.io.tmpdir"));//默认临时文件夹

                // 2. 创建ServletFileUpload对象，并设置上传文件的大小限制。
                ServletFileUpload sfu = new ServletFileUpload(factory);
                sfu.setSizeMax(100 * 1024 * 1024);// 以byte为单位 不能超过10M 1024byte =
                // 1kb 1024kb=1M 1024M = 1G
                sfu.setHeaderEncoding("utf-8");

                // 3.
                // 调用ServletFileUpload.parseRequest方法解析request对象，得到一个保存了所有上传内容的List对象。
                @SuppressWarnings("unchecked")
                List<FileItem> fileItemList = sfu.parseRequest(request);
                Iterator<FileItem> fileItems = fileItemList.iterator();

                // 4. 遍历list，每迭代一个FileItem对象，调用其isFormField方法判断是否是上传文件
                while (fileItems.hasNext()) {
                    FileItem fileItem = fileItems.next();
                    // 普通表单元素
                    if (fileItem.isFormField()) {
                        String name = fileItem.getFieldName();// name属性值
                        String value = fileItem.getString("utf-8");// name对应的value值
                    }
                    // <input type="file">的上传文件的元素
                    else {
                        if (fileItem.getName() != null && fileItem.getName() != "") {
                            String fileName = fileItem.getName();// 文件名称
                            String suffix = fileName.substring(fileName.lastIndexOf('.'));
                            // 新文件名（唯一）
                            String newFileName = new Date().getTime() + suffix;
                            // 5. 调用FileItem的write()方法，写入文件
                            File file = new File("C:/Ming/" + newFileName);
                            System.out.println(file.getAbsolutePath());
                            fileItem.write(file);
                            // 6. 调用FileItem的delete()方法，删除临时文件
                            fileItem.delete();
                            /*
                             * 存储到数据库时注意 1.保存源文件名称 Koala.jpg 2.保存相对路径
                             * image/1478509873038.jpg
                             *
                             */
                            if (user != null) {
                                UserInfo userInfo = new UserInfo();
                                userInfo.setUserId((String) user);
                                userInfo.setPicture(newFileName);
                                workPS.picture(userInfo);
                            } else {
                            }

                        }
                    }
                }
                response.sendRedirect(request.getContextPath() + "/information");
            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

    }

    /**
     * 个人信息
     */
    @RequestMapping("/information")
    public String information(Model model, HttpSession session) {
        try {
            Object userId = session.getAttribute("userId");
            String srcBase = personS.getImgFileToBase64((String) userId);
            model.addAttribute("srcBase", srcBase);
            UserInfo usi = workPS.getPersonMessage((String) userId);
            model.addAttribute("userId", usi.getUserId());
            model.addAttribute("aiName", usi.getAiName());
            model.addAttribute("email", usi.getEmail());
            model.addAttribute("remark", usi.getRemark());
        } catch (Exception e) {

        }
        return "pages_profile";
    }

    /**
     * 修改信息
     */
    @RequestMapping("/personMessage")
    @ResponseBody
    public R personMessage(@RequestBody UserInfo userInfo, HttpSession session) {
        try {
            Object userId = session.getAttribute("userId");
            userInfo.setUserId((String) userId);
            personS.personMessage(userInfo);
            return R.ok().message("修改成功");
        } catch (Exception e) {
            return R.error().message("修改失败");
        }
    }

    /**
     * 修改密码页面
     */
    @RequestMapping("/changePwd")
    public String changePwd(HttpSession session, Model model) {
        try {
            Object userId = session.getAttribute("userId");
            UserInfo usi = workPS.getPersonMessage((String) userId);
            model.addAttribute("aiName", usi.getAiName());
            String srcBase = personS.getImgFileToBase64((String) userId);
            model.addAttribute("srcBase", srcBase);
        } catch (Exception e) {
        }

        return "pages_edit_pwd";
    }

    /**
     * 修改密码接口
     */
    @RequestMapping("/passwordChange")
    @ResponseBody
    public R passwordChange(@RequestBody Login login, HttpSession session) {
        try {
            Object userId = session.getAttribute("userId");
            login.setUserId((String) userId);
            String password = loginService.getPassword(login);
            String oldPassword = Md5Util.StringInMd5(login.getOldPwd());
            if (oldPassword.equals(password)) {
                login.setPassword(Md5Util.StringInMd5(login.getPassword()));
                loginService.changePwd(login);
                return R.ok().message("修改成功");
            } else {
                return R.error().message("原密码错误");
            }
        } catch (Exception e) {
            return R.error().message("修改失败");
        }
    }
}
